package org.zw.android.framework.async;

import android.content.Context;
import android.os.Handler;
import android.os.Message;

/**
 * Asynchronous Task Hanlder
 * 
 * @author zhouwei
 *
 */
public abstract class AsyncTaskHandler extends Handler {
	
	public static final int MSG_STATUS_START			= 0x0ff001 ;
	public static final int MSG_STATUS_FINISH			= MSG_STATUS_START + 1 ;
	public static final int MSG_STATUS_CANCEL			= MSG_STATUS_FINISH + 1 ;
	public static final int MSG_STATUS_ERROR			= MSG_STATUS_CANCEL + 1 ;
	public static final int MSG_STATUS_COMPLETED		= MSG_STATUS_ERROR + 1 ;
	
	protected Context		mContext ;
	private Worker			mWorker ;
	
	public AsyncTaskHandler(){
		this(null);
	}
	
	public AsyncTaskHandler(Context context){
		mContext	= context ;
	}
	
	protected void attachWorker(Worker work){
		mWorker	= work ;
	}
	
	public Worker getWorker(){
		return mWorker ;
	}
	
	@Override
	public final void handleMessage(Message msg) {
		
		// When task cancel, calling sequence is end
		switch(msg.what){
		case MSG_STATUS_CANCEL :
			notifyCancel(msg);
			break ;
		case MSG_STATUS_ERROR :
			notifyError(msg);
			break ;
		default :
			notifyUI(msg);
			break ;
		}
	}
	
	// Subclass override the method
	protected abstract void notifyUI(Message msg) ;
	
	// Subclass override the method
	protected abstract void notifyError(Message msg) ;
	
	// cancel message
	protected abstract void notifyCancel(Message msg) ;
	
	public void sendMessage(int what){
		obtainMessage(what).sendToTarget() ;
	}
	
	public void sendMessage(int what, Object obj){
		obtainMessage(what, obj).sendToTarget() ;
	}
	
	public void sendMessage(int what, int arg0, int arg1){
		obtainMessage(what, arg0,arg1).sendToTarget() ;
	}
	
	/**
	 * Send error message
	 * @param obj
	 */
	public void sendErrorMessage(Object obj){
		obtainMessage(MSG_STATUS_ERROR,obj).sendToTarget() ;
	}
}
